from bs4 import BeautifulSoup
from functools import wraps
import requests
import os
import sys
import time
import Settings
import asyncio



def getSoup(url):
    """获取页面bs解析文件soup"""
    html = requests.get(url, headers=Settings.HOSTREFERER,
                        proxies = Settings.proxies)
    html.encoding = 'gb2312'
    return BeautifulSoup(html.text, 'html.parser')

def chdir(path):
    """进入指定路径，路径如不存在则创建"""
    os.chdir(sys.path[0])  #定位当前路径为执行脚本路径
    if os.path.exists(path) == False:   #如果路径不存在
        os.makedirs(path)               #创建路径
    os.chdir(path)                      #进入路径

async def carwlPic(pic_name, pic_url):  #创建原声协程对象函数
    """爬取图片并保存"""    
    print(time.ctime(),"\t",pic_name)   #输出时间和名称
    jpg = requests.get(pic_url,headers=Settings.HOSTREFERER)
    jpg_name = pic_name+".jpg"
    with open(jpg_name, "wb") as j:
        j.write(jpg.content)
        j.close

async def waitCarwlPic(pic_name, pic_url):
    """创建协程任务,把原生协程对象装入任务中"""
    await carwlPic(pic_name, pic_url)
    
async def asy(list):
    """创建协程任务包，把协程任务列表装入任务包"""
    await asyncio.wait(list)

def timer(func):
    """装饰器：计时器"""
    @wraps(func)
    def watchdog(*arge, **kwargs):
        startime = time.time()
        func(*arge, **kwargs)
        print('\n爬取任务完成，共用时 %d 秒。'%(time.time() - startime))
    return watchdog